var ika = require('ika');
var effects = require('./effects');

function PhotoBooth() {
  ika.Element.call(this);
  this.width = 480;
  this.height = 360;
  this.video = document.createElement('video');
  this.bc = document.createElement('canvas');
  this.bc.width = 480;
  this.bc.height = 360;
  this.bctx = this.bc.getContext('2d');
  this.effectLists = [];
  this.enabledEffects = {};
}

PhotoBooth.prototype = new ika.Element();

PhotoBooth.prototype.init = function() {
  ika.Element.prototype.init.call(this);
  for (var k in effects) {
    this.addEffect(k, effects[k]);
  }
  var self = this;
  navigator.webkitGetUserMedia({video: true}, function(stream){
    var src = webkitURL.createObjectURL(stream);
    self.video.src = src;
    self.emit('ready');
  });
  return this;
};

PhotoBooth.prototype.render = function(ctx) {
  this.bctx.drawImage(this.video, 0, 0, this.width, this.height);
  var idata = this.bctx.getImageData(0, 0, this.width, this.height);
  for (var k in this.enabledEffects) {
    this['_handle_' + k](idata.data, this.enabledEffects[k]);
  }
  ctx.putImageData(idata, this.x, this.y);
};

PhotoBooth.prototype.enableEffect = function(efName, opt) {
  opt = opt || {};
  this.enabledEffects[efName] = opt;
};

PhotoBooth.prototype.disableEffect = function(efName) {
  delete this.enabledEffects[efName];
};

PhotoBooth.prototype.addEffect = function(efName, fn) {
  this.effectLists.push(efName);
  this['_handle_' + efName] = fn;
};

PhotoBooth.prototype.play = function() {
  this.video.play();
};

PhotoBooth.prototype.pause = function() {
  this.video.pause();
};

module.exports = PhotoBooth;